//
//  CWHomePictureView.swift
//  CWWeibo06
//
//  Created by ycw on 2017/7/28.
//  Copyright © 2017年 xiaowei. All rights reserved.
//

import UIKit
import YYWebImage
import SDWebImage

let itemMargin: CGFloat = 5

let itemWidth: CGFloat = (screenWidth - homeCellMargin * 2 - itemMargin * 2)/3

/**
 首页的配图视图
 */

class CWHomePictureView: UICollectionView {
    
    var picURLs: [CWHomePicInfo]? {
        
        didSet{
            calculatePictureSize(pictureCount: picURLs?.count ?? 0)
            reloadData()
        }
    }

    override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
        let flowLayout = UICollectionViewFlowLayout()
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
        super.init(frame: frame, collectionViewLayout: flowLayout)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        dataSource = self
        delegate = self
        self.register(CWHomePictureViewCell.self, forCellWithReuseIdentifier: pictureID)
    }
    
    //MARK: 根据图片的个数计算图片的大小
    private func calculatePictureSize(pictureCount: Int) {
        //判断是否是单张图片
        if pictureCount == 1 {
            //取单张图片
            if let localImage = SDWebImageManager.shared().imageCache.imageFromDiskCache(forKey: picURLs?.first?.thumbnail_pic) {
                //图片过窄的处理
                var imageSize = localImage.size
                if imageSize.width < 80 {
                    let currentWidth: CGFloat = 80
                    var currentHeight = currentWidth / localImage.size.width * localImage.size.height
                    //如果图片过高
                    if currentHeight > 150 {
                        currentHeight = 150
                    }
                    imageSize = CGSize(width: currentWidth, height: currentHeight)
                }
                
                self.snp.makeConstraints({ (make) in
                    make.size.equalTo(imageSize)
                })
                //修改item的大小
                let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
                flowLayout.itemSize = imageSize
                
                return
            }
        }
        
        let cols: Int = pictureCount > 3 ? 3 : pictureCount
        
        let rows: Int = (pictureCount - 1) / 3 + 1
        
        //计算配图的宽度
        let pictureViewWidth: CGFloat = itemWidth * CGFloat(cols) + CGFloat(cols - 1) * itemMargin
        
        //计算配图视图的高度
        let pictureViewHeight: CGFloat = itemWidth * CGFloat(rows) + CGFloat(rows - 1) * itemMargin
        
        //更新配图大小
        self.snp.updateConstraints { (make) in
            make.size.equalTo(CGSize(width: pictureViewWidth, height: pictureViewHeight))
        }
        
        //如果不是单张图片，需要把size修改回去
        let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
        flowLayout.itemSize = CGSize(width: itemWidth, height: itemWidth)
        flowLayout.minimumLineSpacing = itemMargin
        flowLayout.minimumInteritemSpacing = itemMargin
    }

}

extension CWHomePictureView: UICollectionViewDelegate,UICollectionViewDataSource {
    
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return 1
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return self.picURLs?.count ?? 0
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: pictureID, for: indexPath) as! CWHomePictureViewCell
        cell.pictureModel = self.picURLs?[indexPath.item]
        return cell
    }
    
}


//MARK: 自定义配图视图的cell类
class CWHomePictureViewCell: UICollectionViewCell {
    
    //MARK: 懒加载控件
    fileprivate lazy var imageView: UIImageView = {
        let imgV: UIImageView = UIImageView(image: UIImage(named: "timeline_image_placeholder"))
        imgV.contentMode = UIViewContentMode.scaleAspectFill
        //超出部分裁剪
        imgV.clipsToBounds = true
        return imgV
        
    }()
    
    //需要显示的数据模型
    var pictureModel: CWHomePicInfo? {
        didSet{
            if let currentModel = pictureModel {
                imageView.yy_setImage(with: URL(string: currentModel.thumbnail_pic!), placeholder: UIImage(named: "timeline_image_placeholder"))
            }
        }
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI() {
        
        addSubview(imageView)
        imageView.snp.makeConstraints { (make) in
            make.edges.equalTo(contentView)
        }
    }
    
}





